<template>
    <div>
        <!-- 面包屑区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 添加按钮 -->
            <el-row id="btnRow">
                <el-col>
                    <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
                </el-col>
            </el-row>
            <!-- 分类列表 -->
            <tree-table :data="cateList" :columns="columns" border stripe show-index :expand-type="false" :selection-type="false">
              <template slot="isOk" slot-scope="scope">
                <i class="el-icon-success" v-if="scope.row.cat_deleted == false" style="color:green"></i>
                <i class="el-icon-error" v-else style="color:red"></i>
              </template>
              <template slot="order" slot-scope="scope">
                <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
                <el-tag v-else-if="scope.row.cat_level == 1" type="warning">二级</el-tag>
                <el-tag v-else type="success">三级</el-tag>
              </template>
              <template slot="operation" slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editCate(scope.row.cat_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
              </template>
            </tree-table>
            <!-- 分页区域 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[3, 5, 10, 15]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加分类的对话框 -->
        <el-dialog
          title="添加分类"
          :visible.sync="addCateDialogVisible"
          width="30%"
          @close="closeCateDialog">
          <el-form :model="addCateForm" ref="addCateFormRef" :rules="addCateFormRules" label-width="100px">
            <el-form-item prop="cat_name" label="分类名称">
              <el-input v-model="addCateForm.cat_name"></el-input>
            </el-form-item>
            <el-form-item label="父级分类">
              <el-cascader
                v-model="selectedKeys"
                :options="parentCateList"
                :props="{ expandTrigger: 'hover',label: 'cat_name',children: 'children',value: 'cat_id',checkStrictly: true }"
                clearable
                @change="parentCateChanged"
                size="small">
              </el-cascader>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addCate">添 加</el-button>
          </span>
        </el-dialog>
        <!-- 编辑分类对话框 -->
        <el-dialog
          title="编辑分类"
          :visible.sync="editCateDialogVisible"
          width="30%"
          :before-close="handleClose">
          <el-form :model="editCateForm" ref="editCateFormRef" :rules="editCateFormRules" label-width="100px">
            <el-form-item prop="cat_name" label="分类名称">
              <el-input v-model="editCateForm.cat_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editCateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editedCate">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类的数据
      cateList: [],
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 总数据条数
      total: 1,
      // 表格列配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前列模板名称
          template: 'isOk'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ],
      // 控制添加分类对话框的显示
      addCateDialogVisible: false,
      // 添加分类表单绑定数据
      addCateForm: {
        cat_name: '',
        // 父级分类ID
        cat_pid: 0,
        // 分类等级
        cat_level: 0
      },
      //  添加分类表单校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 6, message: '分类名称为2~6位', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择器选中项的id
      selectedKeys: [],
      // 编辑分类表单绑定数据
      editCateForm: {
        id: 0,
        cat_name: ''
      },
      // 控制编辑分类对话框的显示
      editCateDialogVisible: false,
      // 编辑分类校验规则
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 6, message: '分类名称为2~6位', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    //   获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('/categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取分类列表数据失败')
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 监听分页模块每页展示数目变化
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getCateList()
    },
    // 监听当前页的变化
    handleCurrentChange (curPage) {
      this.queryInfo.pagenum = curPage
      this.getCateList()
    },
    // 监听添加分类按钮
    showAddCateDialog () {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    // 监听对话框关闭重置表单
    closeCateDialog () {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('/categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类列表失败')
      this.parentCateList = res.data
    },
    // 级联选择器选中节点变化时触发
    parentCateChanged () {
      // 如果selectedKeys长度大于0,那么说明选中了父级分类,否则未选中
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 发送请求添加分类
    addCate () {
      this.$refs.addCateFormRef.validate(async (valid, error) => {
        if (!valid) return this.$message.error('请输入正确的分类名称')
        const { data: res } = await this.$http.post('/categories', this.addCateForm)
        if (res.meta.status !== 201) return this.$message.error('添加分类失败')
        this.getCateList()
        this.$message.success('添加分类成功')
        this.addCateDialogVisible = false
      })
    },
    // 编辑分类按钮
    async editCate (id) {
      const { data: res } = await this.$http.get('/categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取分类失败')
      this.editCateForm.id = id
      this.editCateForm.cat_name = res.data.cat_name
      this.editCateDialogVisible = true
    },
    // 发生请求修改分类
    async editedCate () {
      const { data: res } = await this.$http.put(`/categories/${this.editCateForm.id}`, {
        cat_name: this.editCateForm.cat_name
      })
      if (res.meta.status !== 200) return this.$message.error('修改分类名称失败')
      this.getCateList()
      this.$message.success('修改分类名称成功')
      this.editCateDialogVisible = false
    },
    // 发送请求删除分类
    async deleteCate (id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'confirm') {
        const { data: res } = await this.$http.delete('/categories/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除分类失败')
        this.getCateList()
        this.$message.success('删除分类成功')
      } else {
        return this.$message.info('已取消删除')
      }
    }
  }
}
</script>

<style lang="less" scoped>
#btnRow {
  margin-bottom: 10px;
}
.el-cascader {
  width: 100%;
}
</style>
